<template>
  <div style="height: 680px;overflow-y: scroll;padding: 0 12px;position: relative;">
    <a-form
        :label-col="{ style: { width: '80px' } }"
        :model="resolution"
        :rules="rules"
        labelAlign="right"
        ref="resolutionFrom"
    >
      <a-form-item label="封面" name="code">
        <a-upload
            name="file"
            list-type="picture-card"
            class="avatar-uploader"
            :show-upload-list="false"
            :action="proxy.UploadUrl"
            @change="handleCover"
        >
          <div v-if="resolution.cover">
            <img :src="proxy.PicPrefixUrl + resolution.cover"  alt="avatar" class="iconPre" />
          </div>
          <div v-else>
            <loading-outlined v-if="loading"></loading-outlined>
            <plus-outlined v-else></plus-outlined>
            <div class="ant-upload-text">上传</div>
          </div>
        </a-upload>
      </a-form-item>
      <a-form-item label="标题" name="title">
        <a-input v-model:value="resolution.title" placeholder="请输入标题" />
      </a-form-item>
      <a-form-item label="描述">
        <div ref="editorRef" style="height: 200px;width: 100%" />
      </a-form-item>
      <a-row>
        <a-col :span="12">
          <a-form-item label="决议类型" name="type">
            <a-select v-model:value="resolution.type" placeholder="请选择决议类型">
              <a-select-option :value="1">管理规约修订</a-select-option>
              <a-select-option :value="2">业主委员会选举</a-select-option>
              <a-select-option :value="3">物业服务质量评价</a-select-option>
              <a-select-option :value="0">其他</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="投票类型" name="voteType">
            <a-select v-model:value="resolution.voteType" placeholder="请选择投票类型">
              <a-select-option :value="0">文字</a-select-option>
              <a-select-option :value="1">图文</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="8">
          <a-form-item label="是否匿名" name="isAnonymity">
            <a-radio-group v-model:value="resolution.isAnonymity">
              <a-radio :value="0">是</a-radio>
              <a-radio :value="1">否</a-radio>
            </a-radio-group>
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="是否多选" name="multiple">
            <a-radio-group v-model:value="resolution.multiple">
              <a-radio :value="0">是</a-radio>
              <a-radio :value="1">否</a-radio>
            </a-radio-group>
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="最多几个" name="atMost">
           <a-input type="number" v-model:value="resolution.atMost" placeholder="请输入最多选几个"></a-input>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="12">
          <a-form-item label="参与方式" name="dec">
            <a-select v-model:value="resolution.dec" placeholder="请选择参与方式">
              <a-select-option :value="1">1天1次</a-select-option>
              <a-select-option :value="0">仅限一次</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="查看方式" name="showWay">
            <a-select v-model:value="resolution.showWay" placeholder="请选择投票类型">
              <a-select-option :value="0">投完可见</a-select-option>
              <a-select-option :value="1">随时可见</a-select-option>
              <a-select-option :value="2">发起人看见</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="12">
          <a-form-item label="开始时间" name="startTime">
            <a-date-picker v-model:value="resolution.startTime" show-time format="YYYY-MM-DD" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="结束时间" name="endTime">
            <a-date-picker v-model:value="resolution.endTime" show-time format="YYYY-MM-DD" />
          </a-form-item>
        </a-col>
      </a-row>
      <a-form-item label="文字选项" v-if="resolution.voteType == 0">
        <a-input v-model:value="option" placeholder="请输入选项" style="z-index: 9;">
          <template #suffix style="z-index: 1000">
            <a-button type="primary" @click="addOption(0)">添加</a-button>
          </template>
        </a-input>
      </a-form-item>
      <a-form-item label="图文选项" v-if="resolution.voteType == 1">
          <a-row :gutter="8">
            <a-col :span="8">
              <a-form-item>
                <a-upload
                    name="file"
                    list-type="picture-card"
                    class="avatar-uploader"
                    :show-upload-list="false"
                    :action="proxy.UploadUrl"
                    @change="handleUpload"
                >
                  <div v-if="imageText.img">
                    <img :src="proxy.PicPrefixUrl + imageText.img"  alt="avatar" class="iconPre" />
                  </div>
                  <div v-else>
                    <loading-outlined v-if="loading"></loading-outlined>
                    <plus-outlined v-else></plus-outlined>
                    <div class="ant-upload-text">上传</div>
                  </div>
                </a-upload>
              </a-form-item>
            </a-col>
            <a-col :span="13" style="display: flex;flex-direction: column;gap: 6px;">
              <a-form-item label="标签">
                <a-input v-model:value="imageText.label" placeholder="请输入标签"></a-input>
              </a-form-item>
              <a-form-item label="描述">
                <a-input v-model:value="imageText.description" placeholder="请输入描述"></a-input>
              </a-form-item>
            </a-col>
            <a-col :span="3" style="display: flex;flex-direction: column;justify-content: center;margin-bottom: 26px">
              <a-button type="primary" @click="addOption(1)">添加</a-button>
            </a-col>
          </a-row>
      </a-form-item>
      <a-form-item label="已添加的项">
       <div style="height: 80px;overflow-y: scroll">
         <a-list :data-source="options" itemLayout="vertical" v-if="resolution.voteType == 0">
           <template #renderItem="{ item }">
             <a-list-item>
               <a-list-item-meta :description="item.label">
               </a-list-item-meta>
             </a-list-item>
           </template>
         </a-list>
         <div v-for="item in options" v-if="resolution.voteType == 1" style="display: flex;flex-wrap: wrap;gap: 12px;flex-direction: row">
             <div style="display: flex;justify-content: flex-start;align-items: center;margin: 6px;">
               <a-image style="border-radius: 50%;" :src="proxy.PicPrefixUrl + item.img" :width="36" :height="36"/>
               <div style="display: flex;flex-direction: column;margin-left: 10px">
                 <span style="font-size: 14px;font-weight: 600;">{{item.label}}</span>
                 <span style="font-size: 12px;opacity: 0.8">{{item.description}}</span>
               </div>
             </div>
         </div>
       </div>
      </a-form-item>
    </a-form>
    <a-space class="functionBox">
      <a-button @click="cancel">取消</a-button>
      <a-button type="primary" @click="submit()">确认</a-button>
    </a-space>
  </div>
</template>

<script setup lang="ts">
    import { ref, onMounted, onUnmounted, getCurrentInstance } from "vue";
    import type { Resolution } from "@/interface/Resolution"
    import { AiEditor } from "aieditor";
    import "aieditor/dist/style.css";
    import { useLoginStore } from "@/stores/loginStore"
    import {LoadingOutlined, PlusOutlined} from "@ant-design/icons-vue";
    import { message, type UploadChangeParam } from "ant-design-vue";

    interface Props {
      resolution: Resolution;
    }

    let param  = withDefaults(defineProps<Props>(),{
      resolution : () => {
        return {
          type: 0,
          voteType: 0,
          multiple: 1
        } as Resolution;
      }
    })

    let resolution = ref({} as Resolution);

    let imageText = ref({
      label: '',
      img: '',
      description: ''
    });

    let option = ref();
    let options = ref([] as any) ;

    let loginStore = useLoginStore();

    let loading = ref(false);

    const handleUpload = (info: UploadChangeParam) => {
      if (info.file.status === 'uploading') {
        loading.value = true;
        return;
      }
      if (info.file.status === 'done') {
        if(info.file.response.code == 200) {
          imageText.value.img = info.file.response.data;
          loading.value = false;
        }else {
          message.error("文件上传失败!");
          loading.value = false;
        }
      }
    };

    const handleCover = (info: UploadChangeParam) => {
      if (info.file.status === 'uploading') {
        loading.value = true;
        return;
      }
      if (info.file.status === 'done') {
        if(info.file.response.code == 200) {
          resolution.value.cover = info.file.response.data;
          loading.value = false;
        }else {
          message.error("文件上传失败!");
          loading.value = false;
        }
      }
    };

    let { proxy } = getCurrentInstance() as any;

    let resolutionFrom = ref();
    let rules = {
      title: [
        { required: true, message: "请输入标题", trigger: "blur" },
      ],
      description: [
        { required: true, message: "请输入描述", trigger: "blur" },
      ],
      type: [
        { required: true, message: "请选择类型", trigger: "change" },
      ],
      voteType: [
        { required: true, message: "请选择投票类型", trigger: "change" },
      ],
      multiple: [
        { required: true, message: "请选择多选", trigger: "change" },
      ],
      startTime: [
        { required: true, message: "请选择开始时间", trigger: "change" },
      ],
      endTime: [
        { required: true, message: "请选择结束时间", trigger: "change" },
      ],
      isAnonymity: [
          { required: true, message: "请选择匿名投票", trigger: "change" },
      ],
      dec: [
          { required: true, message: "请选择参与方式", trigger: "blur" },
      ],
      atMost: [
          { required: true, message: "请输入最多可投几人", trigger: "blur" },
      ]
    };

    let editorRef = ref();
    let aiEditor: AiEditor | null = null;
    onMounted(() => {
      if(param.resolution.options) {
        options.value = JSON.parse(param.resolution.options).splice(',');
      }
      aiEditor = new AiEditor({
        element: editorRef.value as Element,
        placeholder: "点击输入内容...",
        content: '',
        image: {
          allowBase64: true,
          defaultSize: 350,
          uploadUrl: proxy.UploadUrl,
          uploadHeaders: {
            "Auth": loginStore.loginInfo.token
          },
          uploader: (file: File, uploadUrl: string, headers: Record<string, any>, formName: string): Promise<Record<string, any>> => {
            const formData = new FormData();
            formData.append("file", file);
            return new Promise((resolve, reject) => {
              fetch(uploadUrl, {
                method: "post",
                headers: {'Accept': 'application/json', ...headers},
                body: formData,
              }).then((resp) => resp.json())
                  .then(json => {
                    if (json.code == 200) {
                      let res = {} as any;
                      res.errorCode = 0;
                      res.data = {
                        src: proxy.PicPrefixUrl + json.data,
                        alt: file.name,
                      }
                      resolve(res);
                    }
                  }).catch((error) => {
                reject(error);
              })
            });
          }
        },
        attachment: {
          uploadUrl: proxy.UploadUrl,
          uploadHeaders: ()=>{
            return {
              "Auth": loginStore.loginInfo.token
            }
          },
          uploader: (file: File, uploadUrl: string, headers: Record<string, any>, formName: string): Promise<Record<string, any>> => {
            const formData = new FormData();
            formData.append("file", file);
            return new Promise((resolve, reject) => {
              fetch(uploadUrl, {
                method: "post",
                headers: {'Accept': 'application/json', ...headers},
                body: formData,
              }).then((resp) => resp.json())
                  .then(json => {
                    if (json.code == 200) {
                      let res = {} as any;
                      res.errorCode = 0;
                      res.data = {
                        href: proxy.PicPrefixUrl + json.data,
                        fileName: file.name,
                      }
                      resolve(res);
                    }
                  }).catch((error) => {
                reject(error);
              })
            });
          }
        },
      });
      if (param.resolution) {
        resolution.value = param.resolution;
        aiEditor.setContent(param.resolution.description);
      }
    })

    let emiter = defineEmits(['submit','cancel']);

    function cancel() {
      emiter('cancel', true);
      resolution.value = {
        type: 0,
        voteType: 0
      } as Resolution;
    }

    function submit() {
      resolutionFrom.value.validate().then(() => {
        if (aiEditor) {
          resolution.value.description = aiEditor.getHtml();
          resolution.value.options = JSON.stringify(options.value);
          if (loginStore.loginInfo.user) {
            resolution.value.pushId = loginStore.loginInfo.user.user.id;
          }
          emiter('submit', resolution.value);
        }
      }).catch( (res : any) => {
        console.log(res);
      });
    }

    function addOption(type : number) {
      if (type == 0 && option.value) {
        options.value.push({
          label: option.value
        });
        option.value = '';
      }else if (type == 1 && imageText.value.label && imageText.value.img){
          options.value.push(imageText.value);
          imageText.value = {
            label: '',
            img: '',
            description: ''
          };
      }
    }

    onUnmounted(() => {
      aiEditor && aiEditor.destroy();
    });

</script>

<style scoped lang="scss">
    .functionBox {
      display: flex;
      justify-content: end;
    }
    ::-webkit-scrollbar {
      width: 8px;
      height: 12px;
    }
    ::-webkit-scrollbar-track-piece {
      background-color: transparent;
      -webkit-border-radius: 6px;
    }
    ::-webkit-scrollbar-thumb:vertical {
      height: 12px;
      background-color: #BDBDBD;
      -webkit-border-radius: 6px;
    }
    ::-webkit-scrollbar-thumb:horizontal {
      width: 8px;
      background-color: #BDBDBD;
      -webkit-border-radius: 6px;
    }

    ::-webkit-scrollbar-thumb:vertical:hover,::-webkit-scrollbar-thumb:horizontal:hover
    {
      background-color: #808080;
    }
    .iconPre {
      height: 100px;
      width: 100px;
      border-radius: 8px;
    }
</style>
